/* var obj1 = {
    a: Array.prototype.unshift,
    b: {
        c: 2,
        d: 3
    },
    e: 4,
    h: {
        i: 5
    }
}
var obj2 = {
    a: 111,
    b: {
        c: 222,
        f: 333
    },
    g: 444,
    h: 666
}
// 实现一个mergeObject(obj1, obj2)方法，得到下面的对象，并转化成JSON输出到#app
var obj = {
    a: 111,
    b: {
        c: 222,
        d: 3,
        f: 333
    },
    e: 4,
    g: 444,
    h: 666
}
 */
let obj1 = {
    a: 1,
    b: {
        c: 2,
        d: 3
    },
    e: 4,
    h: {
        i: 5
    }
}
let obj2 = {
    a: 111,
    b: {
        c: 222,
        f: 333,
        h : {
            j:1
        }
    },
    g: 444,
    h: 666
}
// obj2覆盖obj1
function mergeObject(obj1,obj2) {
    for (let item in obj2) {
        let t1 = obj1[item] instanceof Object;
        let t2 = obj2[item] instanceof Object;
        let r1 = obj1[item]
        let r2 = obj2[item]
        if (t1 && t2) {
            mergeObject(obj1[item], obj2[item])
        }
        // 即两者的类型不同
        else if (t1 || t2){
            // 后覆盖前
            obj1[item] = obj2[item]
        }
        // 说明两个都不是对象 才比较key
        else {
            // 两个对象都有同样的key 或者obj1没有但obj2有
            if ((r1 !== undefined && r2 !== undefined) || (r1 === undefined && r2 !== undefined)) {
                obj1[item] = obj2[item]
            }
        }

    }
    return obj1
}

console.log(mergeObject(obj1, obj2));

